from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List

from db.session import get_db
from schemas.task import Task, TaskCreate, TaskUpdate
from crud.task import TaskService

router = APIRouter(
    prefix="/tasks",
    tags=["tasks"]
)

@router.get("/{task_id}", response_model=Task)
def get_task(task_id: str, db: Session = Depends(get_db)):
    db_task = TaskService.get_task(db, task_id)
    if db_task is None:
        raise HTTPException(status_code=404, detail="Task not found")
    return db_task

@router.get("/", response_model=List[Task])
def get_tasks(limit: int = 100, db: Session = Depends(get_db)):
    tasks = TaskService.get_tasks(db, limit=limit)
    return tasks

@router.post("/", response_model=Task)
def create_task(task: TaskCreate, db: Session = Depends(get_db)):
    return TaskService.create_task(db, task)

@router.put("/{task_id}", response_model=Task)
def update_task(task_id: str, task: TaskUpdate, db: Session = Depends(get_db)):
    db_task = TaskService.update_task(db, task_id, task)
    if db_task is None:
        raise HTTPException(status_code=404, detail="Task not found")
    return db_task

@router.delete("/{task_id}")
def delete_task(task_id: str, db: Session = Depends(get_db)):
    success = TaskService.delete_task(db, task_id)
    if not success:
        raise HTTPException(status_code=404, detail="Task not found")
    return {"message": "Task deleted successfully"} 